using CMS.Domain.Entity;
using CMS.Infrastructrue.Persistence;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

using CMS.Application.Common.Interface;

namespace CMS.Infrastructrue
{

    
    public static class ApplicationStartup
    {
        
      

        public static async void MigrateDatabase(this WebApplication app)
        {
            using var scope = app.Services.CreateScope();
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<CMSDbContext>();

                // 自动同步迁移文件到数据库服务器，前提是必须先（手动）生成迁移文件
                context.Database.Migrate();

                var appUserRes = services.GetRequiredService<IRepository<Users>>();
                var appAvatarRes = services.GetRequiredService<IRepository<Avatar>>();

                //如果没有任何图片则先添加一张
                if (!appAvatarRes.Table.Any())
                {
                    var avatar = new Avatar
                    {
                        OriginName = " 2.jpg",
                        CurrentName = "  0c4d6e4da9ee423d9bbc2abdf481ffe2.jpg",
                        RelativePath = "StaticFile/0c4d6e4da9ee423d9bbc2abdf481ffe2.jpg",
                        FileType = "image/jpeg "
                    };
                    await appAvatarRes.AddAsync(avatar);
                }
                // 如果没有任何角色，则生成种子数据
                if (!appUserRes.Table.Any())
                {
                    
                    var user = new Users
                    {
                        UserName = "admin",
                        PassWord = "123",
                        Email = "2903977615@qqcom",
                        AvatarId= appAvatarRes.Table.FirstOrDefault().Id,
                        IsAdministor = true,
                    };

                    await appUserRes.AddAsync(user);

                }
            }
            catch (Exception ex)
            {
                throw new Exception($"An error occurred migrating the DB: {ex.Message}");
            }
        }
    }
}